/*
 *The code is written by NaLi, All rights reserved.
 */
package com.nali.dal.statement.upsert;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;

import com.nali.dal.statement.function.Function;
import com.nali.dal.statement.function.FunctionArgument;
import com.nali.dal.statement.function.FunctionBuilder;
import com.nali.dal.statement.util.DalCollectionUtils;

/**
 * @author gavin Created on 2011-4-11
 */
@Deprecated
public class UpsertStatement implements InitializingBean {
	private List<String> upsert;
	private List<String> identitfiedBy;
	private List<String> count;
	private List<String> sum;
	private List<String> set;
	private boolean needIdentified;

	public List<String> getUpsert() {
		return upsert;
	}

	public void setUpsert(List<String> upsert) {
		this.upsert = upsert;
	}

	public List<String> getIdentitfiedBy() {
		return identitfiedBy;
	}

	public void setIdentitfiedBy(List<String> identitfiedBy) {
		this.identitfiedBy = identitfiedBy;
	}

	public List<String> getCount() {
		return count;
	}

	public void setCount(List<String> count) {
		this.count = count;
	}

	public List<String> getSum() {
		return sum;
	}

	public void setSum(List<String> sum) {
		this.sum = sum;
	}

	public List<String> getSet() {
		return set;
	}

	public void setSet(List<String> set) {
		this.set = set;
	}

	public boolean isNeedIdentified() {
		return needIdentified;
	}

	public void setNeedIdentified(boolean needIdentified) {
		this.needIdentified = needIdentified;
	}

	@Override
	public void afterPropertiesSet() throws Exception {

		if (!DalCollectionUtils.isEmpty(upsert)) {
			for (String value : upsert) {
				Function function = FunctionBuilder.complie(value);
				String name = function.getName();
				List<FunctionArgument> arguments = function.getArgConfigs();
				if (!DalCollectionUtils.isEmpty(arguments)) {
					if (arguments.size() == 1) {
						FunctionArgument functionArgument = arguments.get(0);
						String column = functionArgument.getColumn();
						if (StringUtils.isEmpty(name)) {
							this.set.add(column);
						} else if ("count".equalsIgnoreCase(value)) {
							this.count.add(column);
							needIdentified = true;
						} else if ("sum".equalsIgnoreCase(value)) {
							this.sum.add(column);
							needIdentified = true;
						} else {
							throw new IllegalArgumentException("Illegal value: " + column + ", not support by system");
						}
					} else {
						throw new IllegalArgumentException("Not support mutiple arguments in recent value statment.");
					}
				}
			}
		}

		if (needIdentified) {
			if (DalCollectionUtils.isEmpty(identitfiedBy)) {
				throw new IllegalArgumentException("IdentitifiedBy must not be empty in your usecase");
			}
		}
	}
}
